﻿using ImageCropper.AppCode.DAL.OWDAROModel;
using ImageCropper.Helpers;
using ImageCropper.UI.UserControls.Controls;
using ImageCropper.Util;
using System;
using System.IO;
using System.Linq;

namespace ImageCropper.UI.UserControls.Components.Utility
{
    public partial class ImageUploader : System.Web.UI.UserControl
    {
        public int ImageID
        {
            get
            {
                return ImageIDHiddenField.Value.IntParse();
            }

            set
            {
                ImageIDHiddenField.Value = value.ToString();
            }
        }

        public string StoragePath
        {
            get
            {
                return StoragePathHiddenField.Value;
            }

            set
            {
                StoragePathHiddenField.Value = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var context = new OWDAROEntities())
                {
                    InitializeImage(context);
                }
            }

            ShowWebImageCheckBox.CheckedChanged += ShowWebImageCheckBox_CheckedChanged;
            FormToolbar1.CustomClick += FormToolbar1_CustomClick;
            SaveToolbar.Save += SaveToolbar_Save;
        }

        private void InitializeImage(OWDAROEntities context)
        {
            UploadedImageEdit.ImageUrl = "~/UI/Themes/Default/Graphics/noproductimageassigned.png";

            var imageQuery = (from set in context.OW_Images where set.ImageID == ImageID select set).FirstOrDefault();

            if (imageQuery != null)
            {
                InitializeImage(imageQuery);
            }
            else
            {
                fancybox.Attributes.Add("href", ResolveClientUrl("~/UI/Themes/Default/Graphics/noproductimageassigned.png"));
                ThumbImage.ImageUrl = "~/UI/Themes/Default/Graphics/noproductimageassigned.png";
            }
        }

        private void InitializeImage(OW_Images entity)
        {
            ShowWebImageCheckBox.Checked = entity.ShowWebImage;

            if (entity.ShowWebImage)
            {
                WebImageURLTextBox.Text = entity.WebImageURL;
                WebImageThumbURLTextBox.Text = entity.WebImageThumbURL;

                fancybox.Attributes.Add("href", ResolveClientUrl(entity.WebImageURL));
                ThumbImage.ImageUrl = entity.WebImageThumbURL;
                WebImageThumbURLTextBox.Visible = true;
                WebImageURLTextBox.Visible = true;
                ImageURLFileUpload.Visible = false;

                EditorLaunchToolbar.Visible = false;
            }
            else
            {
                fancybox.Attributes.Add("href", ResolveClientUrl(entity.ImageURL));
                ThumbImage.ImageUrl = entity.ImageThumbURL;
                WebImageThumbURLTextBox.Visible = false;
                WebImageURLTextBox.Visible = false;
                ImageURLFileUpload.Visible = true;

                InitializeCropEditor(entity);
            }
        }

        private void InitializeCropEditor(OW_Images entity)
        {
            UploadedImageEdit.ImageUrl = entity.ImageURL;
            EditorLaunchToolbar.Visible = true;

            decimal aspectRatio = (Convert.ToDecimal(entity.Width) / Convert.ToDecimal(entity.Height));

            OriginalAspectRatioHiddenField.Value = ImageCropAspectRatioHiddenField.Value = aspectRatio.ToString("#.#");

            ImageCropHeight.Value = entity.Height.ToString();
            ImageCropWidth.Value = entity.Width.ToString();

            string styelText = string.Empty;

            AspectrationDisableCheckBox.Checked = false;
        }

        private void SaveToolbar_Save(object sender, EventArgs e)
        {
            using (var context = new OWDAROEntities())
            {
                var entity = (from set in context.OW_Images where set.ImageID == ImageID select set).FirstOrDefault();

                if (entity != null)
                {
                    string oldFilePath = entity.ImageURL;
                    string fileName = Guid.NewGuid().ToString();
                    string fullFileName = fileName + Path.GetExtension(entity.ImageURL);

                    string relativeStoragePath = StoragePath;

                    string relativeFullFilePath = Path.Combine(relativeStoragePath, fullFileName);

                    try
                    {
                        System.Drawing.Image originalImage;

                        if (ImageQualitySlider.Value != 100)
                        {
                            Stream compressedStream = ImageHelper.Compress((int)ImageQualitySlider.Value, ImageHelper.GetStreamFromFile(Server.MapPath(entity.ImageURL)));
                            originalImage = System.Drawing.Image.FromStream(compressedStream);
                        }
                        else
                        {
                            originalImage = System.Drawing.Image.FromFile(Server.MapPath(oldFilePath));
                        }

                        Stream croppedStream = ImageHelper.Crop(originalImage, ImageCropWidth.Value.IntParse(), ImageCropHeight.Value.IntParse(), ImageCropX1.Value.IntParse(), ImageCropY1.Value.IntParse());

                        if (!string.IsNullOrWhiteSpace(ResizeWidthTextBox.Text) || !string.IsNullOrWhiteSpace(ResizeHeightTextBox.Text))
                        {
                            System.Drawing.Image croppedImage = System.Drawing.Image.FromStream(croppedStream);
                            ImageHelper.ResizeImage(croppedImage, Server.MapPath(relativeFullFilePath), ResizeWidthTextBox.Text.IntParse(), ResizeHeightTextBox.Text.IntParse(), ResizePreserveAspectRatioCheckBox.Checked, (int)ImageQualitySlider.Value);

                            SetNewHeightAndWidth(ImageHelper.GetStreamFromFile(Server.MapPath(relativeFullFilePath)));
                        }
                        else
                        {
                            ImageHelper.Save(croppedStream, Server.MapPath(relativeFullFilePath));

                            SetNewHeightAndWidth(croppedStream);
                        }

                        try
                        {
                            entity.ImageURL = relativeFullFilePath;
                            entity.Width = UploadedImageWidthHiddenField.Value.IntParse();
                            entity.Height = UploadedImageHeightHiddenField.Value.IntParse();

                            context.SaveChanges();

                            InitializeImage(entity);

                            ImageCropX1.Value = "0";
                            ImageCropY1.Value = "0";
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                            relativeFullFilePath.DeleteFile();
                        }

                        croppedStream.Dispose();
                        originalImage.Dispose();
                        oldFilePath.DeleteFile();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }

        private void FormToolbar1_CustomClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                using (var context = new OWDAROEntities())
                {
                    var imageQuery = (from set in context.OW_Images where set.ImageID == ImageID select set).FirstOrDefault();

                    if (imageQuery != null)
                    {
                        imageQuery.ShowWebImage = ShowWebImageCheckBox.Checked;

                        if (ShowWebImageCheckBox.Checked)
                        {
                            imageQuery.WebImageURL = WebImageURLTextBox.Text;
                            imageQuery.WebImageThumbURL = (string.IsNullOrWhiteSpace(WebImageThumbURLTextBox.Text)) ? WebImageURLTextBox.Text : WebImageThumbURLTextBox.Text;

                            if (Save(imageQuery, context))
                            {
                                InitializeImage(imageQuery);
                            }
                        }
                        else
                        {
                            if (ImageURLFileUpload.HasFile)
                            {
                                string newImageURL = GetUploadedImagePath(ImageURLFileUpload);
                                string newImageThumbURL = GetUploadedImageThumbPath(ImageURLFileUpload);
                                string oldImageURL = imageQuery.ImageURL;
                                string oldImageThumbURL = imageQuery.ImageThumbURL;

                                if (ImageURLFileUpload.Success)
                                {
                                    imageQuery.ImageURL = newImageURL;
                                    imageQuery.ImageThumbURL = newImageThumbURL;
                                    imageQuery.Width = UploadedImageWidthHiddenField.Value.IntParse();
                                    imageQuery.Height = UploadedImageHeightHiddenField.Value.IntParse();

                                    if (Save(imageQuery, context))
                                    {
                                        InitializeImage(imageQuery);

                                        oldImageURL.DeleteFile();
                                        oldImageThumbURL.DeleteFile();
                                    }
                                    else
                                    {
                                        newImageThumbURL.DeleteFile();
                                        newImageURL.DeleteFile();
                                    }
                                }
                                else
                                {
                                    //SHOW ImageURLFileUpload.Message;
                                }
                            }
                        }
                    }
                    else
                    {
                        OW_Images entity = new OW_Images();
                        entity.ShowWebImage = ShowWebImageCheckBox.Checked;

                        if (ShowWebImageCheckBox.Checked)
                        {
                            entity.WebImageURL = WebImageURLTextBox.Text;
                            entity.WebImageThumbURL = (string.IsNullOrWhiteSpace(WebImageThumbURLTextBox.Text)) ? WebImageURLTextBox.Text : WebImageThumbURLTextBox.Text;

                            if (Add(context, entity))
                            {
                                InitializeImage(entity);
                            }
                        }
                        else
                        {
                            entity.ImageURL = GetUploadedImagePath(ImageURLFileUpload);
                            entity.ImageThumbURL = GetUploadedImageThumbPath(ImageURLFileUpload);

                            if (ImageURLFileUpload.Success)
                            {
                                entity.Width = UploadedImageWidthHiddenField.Value.IntParse();
                                entity.Height = UploadedImageHeightHiddenField.Value.IntParse();

                                if (Add(context, entity))
                                {
                                    InitializeImage(entity);
                                }
                            }
                            else
                            {
                                //SHOW ImageURLFileUpload.Message;
                            }
                        }
                    }
                }
            }
        }

        protected void ShowWebImageCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (ShowWebImageCheckBox.Checked)
            {
                WebImageThumbURLTextBox.Visible = true;
                WebImageURLTextBox.Visible = true;
                ImageURLFileUpload.Visible = false;
            }
            else
            {
                WebImageThumbURLTextBox.Visible = false;
                WebImageURLTextBox.Visible = false;
                ImageURLFileUpload.Visible = true;
            }
        }

        private bool Save(OW_Images imageQuery, OWDAROEntities context)
        {
            try
            {
                context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private bool Add(OWDAROEntities context, OW_Images entity)
        {
            try
            {
                context.OW_Images.Add(entity);
                context.SaveChanges();

                ImageID = entity.ImageID;

                return true;
            }
            catch (Exception ex)
            {
                if (ImageURLFileUpload.Success)
                {
                    entity.ImageURL.DeleteFile();
                    entity.ImageThumbURL.DeleteFile();
                }

                return false;
            }
        }

        private string GetUploadedImagePath(FileUploadAdv fileUpload)
        {
            if (!fileUpload.HasFile)
            {
                return string.Empty;
            }

            string fileName = Guid.NewGuid().ToString();
            string fullFileName = fileName + fileUpload.FileExtension;

            string relativeStoragePath = StoragePath;

            string relativeFullFilePath = Path.Combine(relativeStoragePath, fullFileName);

            fileUpload.FilePath = relativeStoragePath;
            fileUpload.FileName = fileName;

            SetNewHeightAndWidth(fileUpload.FileContent);

            fileUpload.Upload();

            return relativeFullFilePath;
        }

        private void SetNewHeightAndWidth(Stream stream)
        {
            int width = 0;
            int height = 0;

            ImageHelper.GetWidthAndHeight(stream, out width, out height);

            UploadedImageWidthHiddenField.Value = width.ToString();
            UploadedImageHeightHiddenField.Value = height.ToString();
        }

        public string GetUploadedImageThumbPath(FileUploadAdv fileUpload)
        {
            if (!fileUpload.Success)
            {
                return string.Empty;
            }

            string fileName = "thumb_" + Guid.NewGuid().ToString();
            string fileExtension = fileUpload.FileExtension;
            string fullFileName = fileName + fileExtension;

            string relativeStoragePath = StoragePath;

            string relativeFullFilePath = Path.Combine(relativeStoragePath, fullFileName);
            string absoluteFullFilePath = fileUpload.Server.MapPath(relativeFullFilePath);

            fileUpload.ResizeAndUpload(300, absoluteFullFilePath, false);

            return relativeFullFilePath;
        }
    }
}